#include <monitor_settings.h>
#include <kdialog.h>
#include <QPushButton>
#include <QApplication>
#include <QGroupBox>
#include <QScreen>
#include <QFrame>
#include <QMessageBox>

MonitorSettings::MonitorSettings(QWidget *parent)
    : KWidget{parent},
      settings("ukui-monitor-overlay", "settings")
{
    setWindowFlags(Qt::Tool | Qt::WindowStaysOnTopHint | Qt::WindowTitleHint);
    setStyleSheet("background-color: rgba(255, 255, 255, 255); color: black;");
    setMinimumWidth(480);

    layout = new QVBoxLayout(this);
    layout->setSpacing(16);
    layout->setContentsMargins(16, 16, 16, 16);

    baseBar()->setLayout(layout);

    iconBar()->setWidgetName("浮动监视器设置");

    // 获取菜单对象
    kdk::KMenuButton* menu = windowButtonBar()->menuButton();

    // 菜单关于按钮
    QAction* aboutAction = menu->aboutAction();
    connect(aboutAction, &QAction::triggered, this, [&](){
        aboutDialogue = createAboutDialog();
        aboutDialogue->show();
    });

    // 菜单退出按钮
    QAction* exitAction = menu->quitAction();
    connect(exitAction, &QAction::triggered, this, [&](){
        QApplication::exit();
    });

    // 显示菜单按钮
    menu->show();

    createOptions();
    // 重置按钮
    createResetButton();
    // 在底部添加关于信息
    createAboutInfo();
    loadSettings();
}

MonitorSettings::~MonitorSettings()
{

}

void MonitorSettings::loadSettings()
{
    settings.beginGroup("Visibility");
    cpuCheckBox->setChecked(settings.value("CPU", true).toBool());
    cpuFreqCheckBox->setChecked(settings.value("CpuFreq").toBool());

    // 未来优化成单独的函数
    bool enabled = cpuFreqCheckBox->isChecked();
    cpuShowTypeComboBox->setEnabled(enabled);
    cpuShowUnitComboBox->setEnabled(enabled);

    if (!enabled)
    {
        cpuShowTypeComboBox->setStyleSheet("QComboBox:disabled { color: gray; background: #f0f0f0; }");
        cpuShowUnitComboBox->setStyleSheet("QComboBox:disabled { color: gray; background: #f0f0f0; }");
    }
    else
    {
        cpuShowTypeComboBox->setStyleSheet("");
        cpuShowUnitComboBox->setStyleSheet("");
    }

    cpuShowTypeComboBox->setCurrentIndex(settings.value("CpuShowType").toInt());
    cpuShowUnitComboBox->setCurrentIndex(settings.value("CpuFreqUnit", 0).toInt());

    memCheckBox->setChecked(settings.value("MEM", true).toBool());
    gpuCoreCheckBox->setChecked(settings.value("GPUCore", true).toBool());
    gpuMemCheckBox->setChecked(settings.value("GPUVRAM", true).toBool());
    gpuCoreTempCheckBox->setChecked(settings.value("GPUCORETEMP", true).toBool());

    fontSizeSlider->setValue(settings.value("FontSize", 15).toInt());
    fontSizeSpinBox->setValue(settings.value("FontSize", 15).toInt());

    fontColor = (settings.value("FontColor", "#ffffff")).toString();
    fontColorPreviewWidget->setStyleSheet(QString("background-color: %1; border: 1px solid gray; border-radius: 4px;").arg(fontColor));

    bgColor = (settings.value("BgColor", "#ffffff")).toString();
    bgColorPreviewWidget->setStyleSheet(QString("background-color: %1; border: 1px solid gray; border-radius: 4px;").arg(bgColor));

    settings.endGroup();
}

void MonitorSettings::saveSettings()
{
    settings.beginGroup("Visibility");
    settings.setValue("CPU", cpuCheckBox->isChecked());
    settings.setValue("CpuFreq", cpuFreqCheckBox->isChecked());
    settings.setValue("CpuShowType", cpuShowTypeComboBox->currentIndex());
    settings.setValue("CpuFreqUnit", cpuShowUnitComboBox->currentIndex());
    settings.setValue("MEM", memCheckBox->isChecked());
    settings.setValue("GPUCore", gpuCoreCheckBox->isChecked());
    settings.setValue("GPUVRAM", gpuMemCheckBox->isChecked());
    settings.setValue("GPUCORETEMP", gpuCoreTempCheckBox->isChecked());

    settings.setValue("FontSize", fontSizeSpinBox->value());
    settings.setValue("FontColor", fontColor);
    settings.setValue("BgColor", bgColor);

    settings.endGroup();
}

bool MonitorSettings::isCpuUsageVisible() const
{
    return cpuCheckBox->isChecked();
}

bool MonitorSettings::isCpuFreqVisible() const
{
    return cpuFreqCheckBox->isChecked();
}

int MonitorSettings::getCpuFreqVisibleType() const
{
    return cpuShowTypeComboBox->currentIndex();
}

CpuMonitor::FreqUnit MonitorSettings::getCpuFreqVisibleUnit() const
{
    return (cpuShowUnitComboBox->currentIndex() == 0) ? CpuMonitor::FreqUnit::MHZ : CpuMonitor::FreqUnit::GHZ;
}

bool MonitorSettings::isMemUsageVisible() const
{
    return memCheckBox->isChecked();
}

bool MonitorSettings::isGpuCoreUsageVisible() const
{
    return gpuCoreCheckBox->isChecked();
}

bool MonitorSettings::isGpuMemUsageVisible() const
{
    return gpuMemCheckBox->isChecked();
}

bool MonitorSettings::isGpuCoreTempVisible() const
{
    return gpuCoreTempCheckBox->isChecked();
}

int MonitorSettings::getFontSize() const
{
    return fontSizeSpinBox->value();
}

QColor MonitorSettings::getFontColor() const
{
    return fontColor;
}

QColor MonitorSettings::getBgColor() const
{
    return bgColor;
}

void MonitorSettings::createOptions()
{
    // 设置组框的通用样式
    QString groupBoxStyle = "QGroupBox { font-weight: bold; margin-top: 12px; } "
                           "QGroupBox::title { subcontrol-origin: margin; left: 10px; padding: 0 5px 0 5px; }";

    // 显示选项组
    QGroupBox *visibleOptionsGroup = new QGroupBox("显示选项", this);
    visibleOptionsGroup->setStyleSheet(groupBoxStyle);
    
    QVBoxLayout *visibleOptionsLayout = new QVBoxLayout(visibleOptionsGroup);
    visibleOptionsLayout->setSpacing(12);
    visibleOptionsLayout->setContentsMargins(12, 20, 12, 12);

    // CPU 相关选项
    cpuCheckBox = new QCheckBox("显示CPU使用率", this);
    cpuFreqCheckBox = new QCheckBox("显示CPU核心频率", this);

    // CPU 显示模式
    QHBoxLayout *cpuShowTypeLayout = new QHBoxLayout();
    QLabel *cpuShowTypeLabel = new QLabel("显示模式:");
    cpuShowTypeComboBox = new QComboBox(this);
    cpuShowTypeComboBox->addItem("显示全部核心频率（详细）");
    cpuShowTypeComboBox->addItem("显示平均频率（简洁）");
    
    cpuShowTypeLayout->addWidget(cpuShowTypeLabel);
    cpuShowTypeLayout->addWidget(cpuShowTypeComboBox);
    cpuShowTypeLayout->addStretch();

    // CPU 频率单位
    QHBoxLayout *cpuShowUnitLayout = new QHBoxLayout();
    QLabel *cpuShowUnitLabel = new QLabel("频率单位:");
    cpuShowUnitComboBox = new QComboBox(this);
    cpuShowUnitComboBox->addItem("MHz");
    cpuShowUnitComboBox->addItem("GHz");
    
    cpuShowUnitLayout->addWidget(cpuShowUnitLabel);
    cpuShowUnitLayout->addWidget(cpuShowUnitComboBox);
    cpuShowUnitLayout->addStretch();

    // 其他显示选项
    memCheckBox = new QCheckBox("显示内存使用率", this);
    gpuCoreCheckBox = new QCheckBox("显示GPU核心使用率", this);
    gpuMemCheckBox = new QCheckBox("显示GPU内存使用率", this);
    gpuCoreTempCheckBox = new QCheckBox("显示GPU核心温度", this);

    // 连接信号
    auto notifyVisibleChange = [=]() {
        saveSettings();
        emit visibilityChanged();
    };

    connect(cpuCheckBox, &QCheckBox::stateChanged, notifyVisibleChange);
    connect(cpuFreqCheckBox, &QCheckBox::stateChanged, notifyVisibleChange);
    connect(cpuFreqCheckBox, &QCheckBox::stateChanged, [&](){
        bool enabled = cpuFreqCheckBox->isChecked();
        cpuShowTypeComboBox->setEnabled(enabled);
        cpuShowUnitComboBox->setEnabled(enabled);

        if (!enabled)
        {
            cpuShowTypeComboBox->setStyleSheet("QComboBox:disabled { color: gray; background: #f0f0f0; }");
            cpuShowUnitComboBox->setStyleSheet("QComboBox:disabled { color: gray; background: #f0f0f0; }");
        }
        else
        {
            cpuShowTypeComboBox->setStyleSheet("");
            cpuShowUnitComboBox->setStyleSheet("");
        }
    });

    connect(cpuShowTypeComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), notifyVisibleChange);
    connect(cpuShowUnitComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), notifyVisibleChange);
    connect(cpuShowUnitComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), [this](){
        emit cpuFreqUnitChanged();
    });

    connect(memCheckBox, &QCheckBox::stateChanged, notifyVisibleChange);
    connect(gpuCoreCheckBox, &QCheckBox::stateChanged, notifyVisibleChange);
    connect(gpuMemCheckBox, &QCheckBox::stateChanged, notifyVisibleChange);
    connect(gpuCoreTempCheckBox, &QCheckBox::stateChanged, notifyVisibleChange);

    // 添加到显示选项布局
    visibleOptionsLayout->addWidget(cpuCheckBox);
    visibleOptionsLayout->addWidget(cpuFreqCheckBox);
    visibleOptionsLayout->addLayout(cpuShowTypeLayout);
    visibleOptionsLayout->addLayout(cpuShowUnitLayout);
    
    // 添加分隔线
    QFrame *separator1 = new QFrame();
    separator1->setFrameShape(QFrame::HLine);
    separator1->setFrameShadow(QFrame::Sunken);
    visibleOptionsLayout->addWidget(separator1);
    
    visibleOptionsLayout->addWidget(memCheckBox);
    
    // // 添加分隔线
    // QFrame *separator2 = new QFrame();
    // separator2->setFrameShape(QFrame::HLine);
    // separator2->setFrameShadow(QFrame::Sunken);
    // visibleOptionsLayout->addWidget(separator2);
    
    visibleOptionsLayout->addWidget(gpuCoreCheckBox);
    visibleOptionsLayout->addWidget(gpuMemCheckBox);
    visibleOptionsLayout->addWidget(gpuCoreTempCheckBox);

    QFrame *separator3 = new QFrame();
    separator3->setFrameShape(QFrame::HLine);
    separator3->setFrameShadow(QFrame::Sunken);
    visibleOptionsLayout->addWidget(separator3);

    // 字体设置组
    QGroupBox *fontSettingsGroup = new QGroupBox("字体设置", this);
    fontSettingsGroup->setStyleSheet(groupBoxStyle);
    
    QVBoxLayout *fontSettingsLayout = new QVBoxLayout(fontSettingsGroup);
    fontSettingsLayout->setSpacing(12);
    fontSettingsLayout->setContentsMargins(12, 20, 12, 12);

    // 字体大小设置
    QHBoxLayout *fontSizeLayout = new QHBoxLayout();
    fontSizeLabel = new QLabel("字体大小:");
    fontSizeSlider = new QSlider(Qt::Horizontal, this);
    fontSizeSlider->setRange(5, 150);
    fontSizeSlider->setValue(15);
    
    fontSizeSpinBox = new QSpinBox(this);
    fontSizeSpinBox->setRange(5, 150);
    fontSizeSpinBox->setValue(15);
    fontSizeSpinBox->setFixedWidth(90);
    
    fontSizeLayout->addWidget(fontSizeLabel);
    fontSizeLayout->addWidget(fontSizeSlider);
    fontSizeLayout->addWidget(fontSizeSpinBox);

    // 字体颜色设置
    QHBoxLayout *fontColorLayout = new QHBoxLayout();
    fontColorLabel = new QLabel("字体颜色:");
    
    fontColorPreviewWidget = new QWidget(this);
    fontColorPreviewWidget->setFixedSize(40, 30);
    fontColorPreviewWidget->setStyleSheet("border: 1px solid gray; border-radius: 4px;");
    
    fontColorSelectButton = new kdk::KBorderButton("选择", this);
    fontColorSelectButton->setFixedWidth(80);
    
    fontColorLayout->addWidget(fontColorLabel);
    fontColorLayout->addWidget(fontColorPreviewWidget);
    fontColorLayout->addWidget(fontColorSelectButton);
    fontColorLayout->addStretch();

    // 连接字体设置信号
    auto notifyFontSizeChange = [=](int value) {
        fontSizeSpinBox->setValue(value);
        fontSizeSlider->setValue(value);
        saveSettings();
        emit fontSizeChanged();
    };

    connect(fontSizeSlider, &QSlider::valueChanged, notifyFontSizeChange);
    connect(fontSizeSpinBox, QOverload<int>::of(&QSpinBox::valueChanged), notifyFontSizeChange);

    connect(fontColorSelectButton, &QPushButton::pressed, [this]() {
        QColor selectedColor = QColorDialog::getColor(fontColor, this);
        if (selectedColor.isValid()) {
            fontColor = selectedColor.name();
            QString styleSheet = QString("background-color: %1; border: 1px solid gray; border-radius: 4px;")
                    .arg(fontColor);
            fontColorPreviewWidget->setStyleSheet(styleSheet);
            emit fontColorChanged();
            saveSettings();
        }
    });

    // 添加到字体设置布局
    fontSettingsLayout->addLayout(fontSizeLayout);
    fontSettingsLayout->addLayout(fontColorLayout);

    // 背景设置组
    QGroupBox *bgSettingsGroup = new QGroupBox("背景设置", this);
    bgSettingsGroup->setStyleSheet(groupBoxStyle);
    
    QVBoxLayout *bgSettingsLayout = new QVBoxLayout(bgSettingsGroup);
    bgSettingsLayout->setSpacing(12);
    bgSettingsLayout->setContentsMargins(12, 20, 12, 12);

    // 背景颜色设置
    QHBoxLayout *bgColorLayout = new QHBoxLayout();
    bgColorLabel = new QLabel("背景颜色:");
    
    bgColorPreviewWidget = new QWidget(this);
    bgColorPreviewWidget->setFixedSize(40, 30);
    bgColorPreviewWidget->setStyleSheet("border: 1px solid gray; border-radius: 4px;");
    
    bgColorSelectButton = new kdk::KBorderButton("选择", this);
    bgColorSelectButton->setFixedWidth(80);
    
    bgColorLayout->addWidget(bgColorLabel);
    bgColorLayout->addWidget(bgColorPreviewWidget);
    bgColorLayout->addWidget(bgColorSelectButton);
    bgColorLayout->addStretch();

    connect(bgColorSelectButton, &QPushButton::pressed, [this]() {
        QColor selectedColor = QColorDialog::getColor(bgColor, this);
        if (selectedColor.isValid()) {
            bgColor = selectedColor.name();
            QString styleSheet = QString("background-color: %1; border: 1px solid gray; border-radius: 4px;")
                    .arg(bgColor);
            bgColorPreviewWidget->setStyleSheet(styleSheet);
            emit bgColorChanged();
            saveSettings();
        }
    });

    bgSettingsLayout->addLayout(bgColorLayout);

    // 添加到主布局
    layout->addWidget(visibleOptionsGroup);
    layout->addWidget(fontSettingsGroup);
    layout->addWidget(bgSettingsGroup);
    layout->addStretch(); // 添加弹性空间使内容靠上显示


}

void MonitorSettings::resetAllSettings()
{
    // 创建确认对话框
    QMessageBox messageBox(this);
    messageBox.setWindowTitle("确认重置");
    messageBox.setText("确定要重置所有设置为默认值吗？");
    messageBox.setInformativeText("此操作将恢复所有显示选项、字体和背景设置到默认状态。");
    messageBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
    messageBox.setDefaultButton(QMessageBox::Yes);
    
    if (messageBox.exec() == QMessageBox::Yes) {
        bool oldState = this->blockSignals(true);
        
        // 重置显示选项到默认值
        cpuCheckBox->setChecked(true);
        cpuFreqCheckBox->setChecked(false);
        cpuShowTypeComboBox->setCurrentIndex(0);
        cpuShowUnitComboBox->setCurrentIndex(0);
        memCheckBox->setChecked(true);
        gpuCoreCheckBox->setChecked(true);
        gpuMemCheckBox->setChecked(true);
        gpuCoreTempCheckBox->setChecked(true);
        
        // 启用频率相关控件（因为默认CPU频率是关闭的）
        bool enabled = cpuFreqCheckBox->isChecked();
        cpuShowTypeComboBox->setEnabled(enabled);
        cpuShowUnitComboBox->setEnabled(enabled);
        if (!enabled) {
            cpuShowTypeComboBox->setStyleSheet("QComboBox:disabled { color: gray; background: #f0f0f0; }");
            cpuShowUnitComboBox->setStyleSheet("QComboBox:disabled { color: gray; background: #f0f0f0; }");
        } else {
            cpuShowTypeComboBox->setStyleSheet("");
            cpuShowUnitComboBox->setStyleSheet("");
        }
        
        // 重置字体设置
        fontSizeSlider->setValue(15);
        fontSizeSpinBox->setValue(15);
        fontColor = "#ffffff";
        fontColorPreviewWidget->setStyleSheet(
            QString("background-color: %1; border: 1px solid gray; border-radius: 4px;").arg(fontColor));
        
        // 重置背景设置
        bgColor = "#000000";
        bgColorPreviewWidget->setStyleSheet(
            QString("background-color: %1; border: 1px solid gray; border-radius: 4px;").arg(bgColor));
        
        // 恢复信号状态
        this->blockSignals(oldState);
        
        // 保存重置后的设置
        saveSettings();
        
        // 发射所有相关信号来更新显示
        emit visibilityChanged();
        emit fontSizeChanged();
        emit fontColorChanged();
        emit bgColorChanged();
        emit cpuFreqUnitChanged();
        
        // 显示成功消息
        QMessageBox::information(this, "重置成功", "所有设置已重置为默认值。");
    }
}

void MonitorSettings::createResetButton()
{
    QHBoxLayout *resetLayout = new QHBoxLayout();
    resetLayout->setContentsMargins(0, 0, 0, 0);
    
    kdk::KBorderButton *resetButton = new kdk::KBorderButton("重置所有设置", this);
    resetButton->setFixedWidth(240);
    
    resetLayout->addStretch();
    resetLayout->addWidget(resetButton);
    resetLayout->addStretch();
    
    layout->addLayout(resetLayout);
    
    connect(resetButton, &QPushButton::clicked, this, &MonitorSettings::resetAllSettings);
}

void MonitorSettings::createAboutInfo()
{
    // 添加分隔线
    QFrame *separator = new QFrame();
    separator->setFrameShape(QFrame::HLine);
    separator->setFrameShadow(QFrame::Sunken);
    layout->addWidget(separator);

    QHBoxLayout *aboutLayout = new QHBoxLayout();
    aboutLayout->setContentsMargins(0, 8, 0, 0);
    
    // 关于信息标签
    QLabel *aboutLabel = new QLabel(this);
    aboutLabel->setText("Monitor Overlay v0.0.1 | Release Date: 2025/10/31");
    aboutLabel->setStyleSheet("color: #666666; font-size: 10px;");
    aboutLabel->setAlignment(Qt::AlignCenter);
    
    aboutLayout->addWidget(aboutLabel);
    
    layout->addLayout(aboutLayout);
}

kdk::KAboutDialog* MonitorSettings::createAboutDialog()
{
    kdk::KAboutDialog* aboutDialogue = new kdk::KAboutDialog();
    //aboutDialogue->setAppPrivacyLabelVisible(true);

    aboutDialogue->setAppSupport("computerlub@163.com");
    aboutDialogue->setWindowTitle("关于");
    aboutDialogue->setAppName("Monitor Overlay");
    aboutDialogue->setAppVersion("版本：0.0.1");
    aboutDialogue->setBodyTextVisiable(true);

    // 不知道为啥不这样设置关闭关于窗口会退出程序，先强制断开所有信号连接
    disconnect(aboutDialogue->closeButton(), &QPushButton::clicked, nullptr, nullptr);
    connect(aboutDialogue->closeButton(), &QPushButton::clicked, this, [&](){
        this->aboutDialogue->hide();
    });
    return aboutDialogue;
}